package my.mall.admin.api.service

import com.github.benmanes.caffeine.cache.Cache
import my.mall.admin.api.enums.CacheKeyConst
import my.mall.common.annotation.Slf4j
import my.mall.common.annotation.Slf4j.Companion.log
import org.springframework.cache.CacheManager
import org.springframework.cache.caffeine.CaffeineCacheManager
import org.springframework.stereotype.Service

@Slf4j
@Service
open class CacheService(
    private val cacheManager: CacheManager
) {

    open fun get(cacheName: String, key: Any): Any? {
        return cacheManager.getCache(cacheName)!!.get(key)
    }

    open fun put(cacheName: String, key: Any, value: Any) {
        cacheManager.getCache(cacheName)!!.put(key, value)
    }

    open fun printStatsInfo() {
        val caffeineCacheManager = cacheManager as CaffeineCacheManager
        CacheKeyConst.javaClass.declaredFields.forEach { field ->
            val fieldName = field.name
            if ("INSTANCE" != fieldName) {
                val cache = caffeineCacheManager.getCache(fieldName)
                val caffeineCache = cache!!.nativeCache as Cache<*, *>
                log.info("Cache $fieldName size: ${caffeineCache.estimatedSize()}, stats info: ${caffeineCache.stats()}")
            }
        }
    }

}